package com.holike.crm.fragment.report;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import pony.xcode.tablayout.CommonTabLayout;
import pony.xcode.tablayout.TabEntity;
import pony.xcode.tablayout.CustomTabEntity;
import pony.xcode.tablayout.OnTabSelectListener;

import com.holike.crm.R;
import com.holike.crm.adapter.AbsFormAdapter;
import com.holike.crm.base.BaseFragment;
import com.holike.crm.base.FragmentHelper;
import com.holike.crm.base.IntentValue;
import com.holike.crm.bean.OnlineDrainageBean;
import com.holike.crm.dialog.CalendarPickerDialog;
import com.holike.crm.dialog.PlainTextTipsDialog;
import com.holike.crm.helper.CalendarPickerHelper;
import com.holike.crm.helper.FormDataHelper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

class OnlineDrainageHelper extends FragmentHelper {
    private Callback mCallback;
    private String mTime;
    private String mType, mCityCode;
    private Date mStartDate, mEndDate;
    private List<Date> mSelectDate;
    private FrameLayout mContainer;
    private Handler mHandler;

    OnlineDrainageHelper(BaseFragment<?, ?> fragment, Callback callback) {
        super(fragment);
        this.mCallback = callback;
        fragment.setTitle(R.string.online_drainage_report_title);
        boolean isContainValue = initBundle(fragment.getArguments());
        initTabLayout();
        mContainer = obtainView(R.id.fl_container);
        if (isContainValue) {
            requestByDelay();
        } else {
            doRequest();
        }
    }

    private boolean initBundle(Bundle bundle) {
        if (bundle != null) {
            mTime = bundle.getString("time");
            mType = bundle.getString("type");
            mCityCode = bundle.getString("cityCode");
            mStartDate = (Date) bundle.getSerializable("startDate");
            mEndDate = (Date) bundle.getSerializable("endDate");
            return true;
        }
        return false;
    }

    private void initTabLayout() {
        CommonTabLayout tabLayout = obtainView(R.id.tab_layout);
        List<CustomTabEntity> tabEntities = new ArrayList<>();
        tabEntities.add(new TabEntity(mContext.getString(R.string.tab_this_month)));
        tabEntities.add(new TabEntity(mContext.getString(R.string.tab_annual)));
        tabEntities.add(new TabEntity(mContext.getString(R.string.tab_query_date)));
        tabLayout.setTabData(tabEntities);
        if (TextUtils.equals(mTime, "1")) { //全年
            tabLayout.setCurrentTab(1);
        } else if (TextUtils.equals(mTime, "2")) { //本月
            tabLayout.setCurrentTab(0);
        } else if (TextUtils.equals(mTime, "3")) { //查询日期
            tabLayout.setCurrentTab(2);
        }
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (position == 0) { //本月
                    mTime = "2";
                    doRequest();
                } else if (position == 1) { //全年
                    mTime = "1";
                    doRequest();
                } else {
                    mTime = "3";
                    onSelectDates();
                }
            }

            @Override
            public void onTabReselect(int position) {
                if (position == 2) {
                    onSelectDates();
                }
            }
        });
    }

    private void onSelectDates() {
        CalendarPickerHelper.showCalendarDialog(mContext, mSelectDate, new CalendarPickerHelper.SimpleCalendarPickerListener() {

            @Override
            public void onCalendarPicker(CalendarPickerDialog dialog, List<Date> selectedDates, Date start, Date end) {
                dialog.dismiss();
                mSelectDate = selectedDates;
                if (!selectedDates.isEmpty()) {
                    mStartDate = start;
                    mEndDate = end;
                    doRequest();
                } else {
                    mStartDate = null;
                    mEndDate = null;
                }
            }
        });
    }

    private void requestByDelay() {
        if (mHandler == null)
            mHandler = new Handler();
        mHandler.postDelayed(this::doRequest, 300);
    }

    void doRequest() {
        mCallback.onRequest(mTime, mType, mCityCode, mStartDate, mEndDate);
    }

    void onSuccess(OnlineDrainageBean bean) {
        mContainer.removeAllViews();
        mFragment.setRightMenu(R.string.customre_conversion_rate, view -> openConversionRate(bean));
        setFormData(bean.getPercentData(), updateTopLayout(bean), bean.isPrice());
    }

    private View updateTopLayout(OnlineDrainageBean bean) {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.include_online_drainage_content, mContainer, true);
        contentView.findViewById(R.id.tv_question_mark).setOnClickListener(view -> showDescription());  //点击“？”弹出数据说明对话框
        ((TextView) contentView.findViewById(R.id.tv_time_detail)).setText(bean.timeData);  //显示时间段
        return contentView;
    }

    private void openConversionRate(OnlineDrainageBean bean) {
        IntentValue.getInstance().put("online-drainage", bean);
        Bundle bundle = new Bundle();
        bundle.putString("time", mTime);
        bundle.putString("type", mType);
        bundle.putString("cityCode", mCityCode);
        bundle.putSerializable("startDate", mStartDate);
        bundle.putSerializable("endDate", mEndDate);
        mFragment.startFragment(new OnlineDrainageRatioFragment(), bundle);
    }

    private void showDescription() {
        new PlainTextTipsDialog(mContext).setData(R.array.online_drainage_tips).show();
    }

    private void setFormData(final List<OnlineDrainageBean.PercentDataBean> dataList, View contentView, final boolean isPrice) {
        FormDataHelper.attachView(contentView, new FormDataHelper.FormDataBinder() {
            @Override
            public int bindFirstColumnLayoutRes() {
                return R.layout.include_form_data_column_60dp;
            }

            @Override
            public CharSequence bindSideTitle() {
                return  mContext.getString(R.string.division);
            }

            @Override
            public int bindFirstRowLayoutRes() {
                return R.layout.include_online_drainage_firstrow;
            }

            @Override
            public RecyclerView.Adapter bindSideAdapter() {
                return new SimpleFormAdapter(mContext, dataList, true, isPrice);
            }

            @Override
            public RecyclerView.Adapter bindContentAdapter() {
                return new SimpleFormAdapter(mContext, dataList, false, isPrice);
            }
        }, new FormDataHelper.SimpleFormDataCallback() {
            @Override
            public void bindFirstRow(View view) {
                view.findViewById(R.id.ll_order_layout).setVisibility(isPrice ? View.VISIBLE : View.GONE);
            }
        });
    }

    private final class SimpleFormAdapter extends AbsFormAdapter<OnlineDrainageBean.PercentDataBean> {
        private boolean mSide;
        private int mLayoutResourceId;
        private int mVisibility;

        SimpleFormAdapter(Context context, List<OnlineDrainageBean.PercentDataBean> dataList, boolean isSide, boolean isPrice) {
            super(context, dataList);
            mSide = isSide;
            mVisibility = isPrice ? View.VISIBLE : View.GONE;
            mLayoutResourceId = mSide ? R.layout.item_online_drainage_form_side : R.layout.item_online_drainage_form_content;
        }

        @Override
        protected void bindViewHolder(RecyclerHolder holder, OnlineDrainageBean.PercentDataBean bean, int position) {
            holder.setText(R.id.tv_division, bean.area); //划分
            holder.setText(R.id.tv_issued_count, bean.customerTotal); //下发客户数
            holder.setText(R.id.tv_effective_customers, bean.customerYes); //有效客户数
            holder.setText(R.id.tv_invalid_customers, bean.customerNo); //无效客户数
            holder.setText(R.id.tv_invalid_rate, bean.customerNoPercent); //无效率
            holder.setText(R.id.tv_scale_count, bean.scaleCount); //量尺数
            holder.setText(R.id.tv_scale_rate, bean.scaleCountPercent); //量尺率
            holder.setText(R.id.tv_earnest_count, bean.earnestCount); //订金数
            holder.setText(R.id.tv_earnest_rate, bean.earnestPercent); //订金转化率
            holder.setText(R.id.tv_earnest_money, bean.earnestMoney); //订金金额
            holder.setText(R.id.tv_order_count, bean.orderCounts); //订单数
            holder.setText(R.id.tv_sign_count, bean.signingCount); //签约数
            holder.setText(R.id.tv_sign_rate, bean.signingCountPercent); //合同转化率
            holder.setText(R.id.tv_sign_money, bean.signingMoney); //签约金额
            holder.setVisibility(R.id.ll_order_layout, mVisibility);
            holder.setText(R.id.tv_order_count, bean.orderCounts); //订单数
            holder.setText(R.id.tv_order_rate, bean.orderPercent); //订单转化率
            holder.setText(R.id.tv_order_money, bean.orderMoney); //订单金额
            setClickableCell(holder, position, R.id.tv_division, mSide && bean.isClickable(), view -> startNextLevel(bean.type, bean.cityCode));
        }

        @Override
        protected int bindView(int viewType) {
            return mLayoutResourceId;
        }
    }

    private void startNextLevel(String type, String cityCode) {
        Bundle bundle = new Bundle();
        bundle.putString("time", mTime);
        bundle.putString("type", type);
        bundle.putString("cityCode", cityCode);
        bundle.putSerializable("startDate", mStartDate);
        bundle.putSerializable("endDate", mEndDate);
        mFragment.startFragment(new OnlineDrainageFragment(), bundle, true);
    }

    void onFailure(String failReason) {
        mContainer.removeAllViews();
        LayoutInflater.from(mContext).inflate(R.layout.include_empty_page, mContainer, true);
        mFragment.noNetwork(failReason);
    }

    void destroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    interface Callback {
        void onRequest(String time, String type, String cityCode, Date startDate, Date endDate);
    }
}
